import torch
import torch.nn as nn
import torch.optim as optim

# 数据
X = torch.tensor([-1.0,  0.0, 1.0, 2.0, 3.0, 4.0])
y = torch.tensor([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0])

# 模型定义


class Perceptron(nn.Module):
    def __init__(self):
        super(Perceptron, self).__init__()
        self.fc = nn.Linear(1, 1)

    def forward(self, x):
        return self.fc(x)


# 实例化模型
model = Perceptron()

# 损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.SGD(model.parameters(), lr=0.01)

# 训练
for epoch in range(1000):
    inputs = X.view(-1, 1)
    labels = y.view(-1, 1)

    optimizer.zero_grad()

    outputs = model(inputs)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()

    if (epoch+1) % 100 == 0:
        print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 1000, loss.item()))
